﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.zmc;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.Zmc.Instrumentkit;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.Zmc.Instrumentkit
{
    public class CreateInstrumentkitCommendHandlers : IRequestHandler<CreateInstrumentkitCommends, ApiResult<int>>
    {

        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public CreateInstrumentkitCommendHandlers(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }


        /// <summary>
        /// 创建器械包数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(CreateInstrumentkitCommends request, CancellationToken cancellationToken)
        {
          

            ApiResult<int> result = new ApiResult<int>();
            using (var tran = db.Ado.UseTran())
            {

                //业务代码
                //里面禁止写 try处理事务逻辑，格式一定按现在的风格来
                try
                {
                    // 1. 插入主表
                    var mainEntity = new Instrumentkits
                    {
                        InstrumentkitsId= request.InstrumentkitsId,
                        InstrumentkitsNo = request.InstrumentkitsNo,
                        InstrumentkitsName = request.InstrumentkitsName,
                        InstrumentkitsType = true,
                        Effectdays = request.Effectdays,
                        Serviceprice = request.Serviceprice,
                        Sterilizamethod = request.Sterilizamethod,
                        Department=request.Department,
                    
                        Outerpackags = request.Outerpackags,

                        State=false,
                        IsDeletes=false,

                    };
                    var mainInsertResult = await db.Insertable(mainEntity).ExecuteReturnIdentityAsync(); // 使用 ExecuteReturnIdentityAsync 获取自增 ID
                    if (mainInsertResult <= 0)
                    {
                        result.Code = ApiEnums.添加失败;
                        result.Msg = "主表插入失败";
                        return result;
                    }
                    var mainId = mainInsertResult; // 获取主表自增 ID
                    if (request.apparatus != null)
                    {
                        // 2. 插入子表
                        foreach (var item in request.apparatus)
                        {
                            var apparas = new Apparatus
                            {
                                ApparatusId=mainId,
                                ApparatusNo = item.ApparatusNo,
                                ApparatusName = item.ApparatusName,
                                Specification = item.Specification,
                                Quantity = item.Quantity,
                                ApparatusModel="QJ"+new Random().Next(1000, 9999),
                                ApparatusNnit="台",
                                ApparatusPrice= "300",
                                Productionindustry ="北京医疗厂商",
                                State=false,
                                IsDeletes =false,
                                Durableproperties = item.Durableproperties,

                                InstrumentkitsId = mainInsertResult // 设置外键 ID
                            };

                            var detailInsertResult = await db.Insertable(apparas).ExecuteCommandAsync();
                            if (detailInsertResult <= 0)
                            {

                                // 子表插入失败，手动删除主表（补偿逻辑，可能再次失败）
                                await db.Deleteable<Instrumentkits>().Where(x => x.InstrumentkitsId == mainId).ExecuteCommandAsync();
                                result.Code = ApiEnums.添加失败;
                                result.Msg = "子表插入失败，已回滚主表";
                                return result;
                            }
                        }
                    }

                    result.Code = ApiEnums.添加成功;
                    result.Msg = "插入成功";
              
                    tran.CommitTran();  //提交事务
                    return result;
                }
                catch (Exception ex)
                {
                    result.Code = ApiEnums.添加失败;
                    result.Msg = $"操作失败：{ex.Message}";
                    tran.RollbackTran();  //回滚事务
                   
                    throw;
                }
              
            }



        }
    }
}
